#include <iostream>

#include "Reactor.hpp"
#include "Listener.hpp"
#include "Channel.hpp"
#include "Log.hpp"
#include "comm.hpp"
#include "Protocol.hpp"
#include "NetCal.hpp"

using namespace LogModule;

int main(int args, char *argv[])
{
    if (args != 2)
    {
        std::cerr << "Usage: " << argv[0] << " port" << std::endl;
        exit(USAGE_ERR);
    }

    Enable_Console_Log_Strategy();

    uint16_t port = std::stoi(argv[1]);

    // 业务模块
    std::shared_ptr<Cal>
        cal = std::make_shared<Cal>();

    // 协议对象
    std::shared_ptr<Protocol>
        protocol = std::make_shared<Protocol>([&cal](Request &req)
                                              { return cal->Execute(req); });

    // listener对象
    std::shared_ptr<Connection>
        listener = std::make_shared<Listener>(port);

    listener->Register([&protocol](std::string &inbuffer) -> std::string
        {
            LOG(LogLevel::DEBUG) << "进入到匿名函数中";
            std::string response_str = "";
            while(true)
            {
                std::string package;
                if(!protocol->Decode(inbuffer, &package))
                    break;
                response_str += protocol->Exeute(package);
            }
            LOG(LogLevel::DEBUG) << "response_str: " << response_str;
            return response_str; 
        });

    std::unique_ptr<Reactor>
        R = std::make_unique<Reactor>();

    R->AddConnection(listener);

    R->Loop();

    return 0;
}